package com.huluobo.a2303mdmdemo.demo

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ObjectAnimator
import android.content.Context
import android.view.animation.AccelerateInterpolator
import android.widget.ImageView
import android.widget.RelativeLayout
import com.huluobo.a2303mdmdemo.R
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.Random
import java.util.Timer
import kotlin.concurrent.timerTask

/**
 *  Created by LC on 2025/9/2.
 */
class RedPackRainView(context: Context) : RelativeLayout(context) {
    //计时器,用于计算间隔多久生成一个雨点
    private lateinit var timer: Timer

    fun start() {
        timer = Timer()
        timer.schedule(timerTask {
            //由于timerTask 处于子线程位置,不能直接修改UI,也就是没办法addView,所以需要切换到主线程
            CoroutineScope(Job()).launch(Dispatchers.Main) {
                //创建一个图片布局
                val iv = ImageView(context)
                //设置图片资源
                iv.setImageResource(R.drawable.like)
                //设置宽高
                val params = LayoutParams(100, 100)
                //设置左边距
                val left = Random().nextInt(980)
                params.topMargin = 0
                params.leftMargin = left
                iv.layoutParams = params

                val animator = ObjectAnimator.ofFloat(iv, "translationY", 0f, 1920f)
                animator.duration = 1000
                animator.interpolator = AccelerateInterpolator()
                animator.addListener(object : AnimatorListenerAdapter() {
                    override fun onAnimationEnd(animation: Animator) {
                        super.onAnimationEnd(animation)
                        //当动画结束时,移除掉iv
                        removeView(iv)
                    }
                })
                animator.start()


                //添加iv到布局上
                addView(iv)
            }
        }, 0, 100)
    }
}